<?php

/* The Chat class exploses public static methods, used by ajax.php */

class Chat{

    public static function login($name,$email){
        if(!$name || !$email){
            throw new Exception('Vyplň všechny položky.');
        }

        if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
            throw new Exception('Neplatný E-mail.');
        }

        // Preparing the gravatar hash:
        $gravatar = md5(strtolower(trim($email)));

        $user = new ChatUser(array(
                'name'		=> $name,
                'gravatar'	=> $gravatar
        ));

        // The save method returns a MySQLi object
        if($user->save()->affected_rows != 1){
            throw new Exception('Nick je v chatu právě používán.');
        }

        $_SESSION['user']	= array(
                'name'		=> $name,
                'gravatar'	=> $gravatar
        );

        return array(
                'status'	=> 1,
                'name'		=> $name,
                'gravatar'	=> Chat::gravatarFromHash($gravatar)
        );
    }

    public static function checkLogged(){
        $response = array('logged' => false);

        if($_SESSION['user']['name']){
            $response['logged'] = true;
            $response['loggedAs'] = array(
                    'name'		=> $_SESSION['user']['name'],
                    'gravatar'	=> Chat::gravatarFromHash($_SESSION['user']['gravatar'])
            );
        }

        return $response;
    }

    public static function logout(){
        DB::query("DELETE FROM webchat_users WHERE name = '".DB::esc($_SESSION['user']['name'])."'");

        $_SESSION = array();
        unset($_SESSION);

        return array('status' => 1);
    }

    public static function submitMessage($chatText, $receiver) {
        /*
        if (!$_SESSION['user']) {

            throw new Exception('Nejsi přihlášen.');
        }
        */

        if (!$chatText) {
            throw new Exception('Nepotvrdil jsi zprávu.');
        }

        $_SESSION['user']['ID'] = 3;
        $_SESSION['user']['gravatar'] = "Something";
        $chat = new ChatLine(array(
                'authorID'	=> $_SESSION['user']['ID'],
                'gravatar'	=> $_SESSION['user']['gravatar'],
                'receiver'	=> $receiver,
                'text'		=> $chatText,
                'time'		=> "".time().""
        ));

        $chat->postMessage();
    }

    public static function getUsers(){

        if($_SESSION['user']['name']){
            $user = new ChatUser(array('name' => $_SESSION['user']['name']));
            $user->update();
        }

        // Deleting chats older than 5 minutes and users inactive for 30 seconds

        DB::query("DELETE FROM webchat_lines WHERE ts < SUBTIME(NOW(),'0:5:0')");
        DB::query("DELETE FROM webchat_users WHERE last_activity < SUBTIME(NOW(),'0:0:30')");

        $result = DB::query('SELECT * FROM webchat_users ORDER BY name ASC LIMIT 18');

        $users = array();
        while($user = $result->fetch_object()){
            $user->gravatar = Chat::gravatarFromHash($user->gravatar,30);
            $users[] = $user;
        }

        return array(
            'users' => $users,
            'total' => DB::query('SELECT COUNT(*) as cnt FROM webchat_users')->fetch_object()->cnt
        );
    }

    public static function getChats($lastID){
        $lastID = (int)$lastID;

        $result = DB::query('SELECT * FROM webchat_lines WHERE id > '.$lastID.' ORDER BY id ASC');

        $chats = array();
        while($chat = $result->fetch_object()){
            // Returning the GMT (UTC) time of the chat creation:
            $chat->time = array(
                'hours'		=> gmdate('H',strtotime($chat->ts)),
                'minutes'	=> gmdate('i',strtotime($chat->ts))
            );

            $chat->gravatar = Chat::gravatarFromHash($chat->gravatar);

            $chats[] = $chat;
        }

        return array('chats' => $chats);
    }

    public static function gravatarFromHash($hash, $size=23){
        return 'http://www.gravatar.com/avatar/'.$hash.'?size='.$size.'&amp;default='.
                urlencode('http://www.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?size='.$size);
    }
    
    public static function showSmileys(){



        $smileys = array("smile" => ":)",
            "frown" => ":(",
            "happy" => ":D");
    }
    
    public static function leaveTheRoom(){
        // WHERE is the WALL object???
        echo $_SESSION['user']['name'] . ' left the room.';
        $_SESSION['user']['name'] = 0;
    }
    
    public static function startTheRoom(){
        // WHERE is the WALL object???
        echo $_SESSION['user']['name'] . ' entered the room.';
        $_SESSION['user']['name'] = 1;
    }
}
?>